import xpath
from xml.dom.minidom import parseString

class XMLParser(object):
    
    #from the api: Artist.search
    def parse_artist_search(self, xmlstring):
        doc = parseString(xmlstring)
        query = xpath.findvalue("//@searchTerms", doc)
        
        artists = []
        artist_nodes = xpath.find("//artist", doc)
        
        for node in artist_nodes:
            name = xpath.findvalue(".//name", node)
            url = None
            if name:
                url = "/results?searchBox="+name.replace(' ', '+')
            image = xpath.findvalue('.//image', node)
            artists.append({"name":name, "url":url, "image":image})
        
        return {"query":query, "artists":artists}
    
    
    #api: Track.search
    def parse_song_search(self, xmlstring):
        doc = parseString(xmlstring)
        query = xpath.findvalue("//@searchTerms", doc)
        
        tracks = []
        track_nodes = xpath.find("//track", doc)
        
        for node in track_nodes:
            name = xpath.findvalue(".//name", node)
            url = xpath.findvalue(".//url", node)
            artist = xpath.findvalue(".//artist", node)
            listeners = xpath.findvalue(".//listeners", node)
            tracks.append({"name":name, "url":url, "artist":artist, "listeners":listeners, "youtube":""})
            
        return {"query":query, "tracks":tracks}
    
    #api: Artist.info
    def parse_artist_info(self, xmlstring):
        doc = parseString(xmlstring)
        artist = {}
         
        artist["name"] = xpath.findvalue("//name", doc)
        artist["url"] = xpath.findvalue("//url", doc)
        artist["image"] = xpath.findvalue('//image[@size="large"]', doc)
        artist["listeners"] = xpath.findvalue("//stats/listeners", doc)
        artist["plays"] = xpath.findvalue("//stats/playcount", doc)
        
        similar = []
        for node in xpath.find("//similar/artist", doc):
            name = xpath.findvalue(".//name", node)
            url = "/results?searchBox="+name.replace(' ', '+')
            similar.append({"name":name, "url":url})
            
        artist["similar"] = similar
        return artist
    
    #api: Artist.getSimilar 
    def parse_get_similar(self, xmlstring):
        doc = parseString(xmlstring)
        
        similar = []
        
        for node in xpath.find('//similarartists/artist', doc):
            name = xpath.findvalue(".//name", node)
            match = xpath.findvalue(".//match", node)
            similar.append({"name":name, "match":float(match)})
            
        return similar
    
    